package com.lanou.pianke.login.service.impl;

import com.alibaba.fastjson.JSON;
import com.lanou.pianke.login.entity.TokenUser;
import com.lanou.pianke.login.entity.User;
import com.lanou.pianke.login.mapper.LoginMapper;
import com.lanou.pianke.login.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private LoginMapper loginMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String login(User user) {

        User user1 = loginMapper.selectUserByunameAndPwd(user);
        if (user1!=null){
            String token = UUID.randomUUID().toString();
            String userString = JSON.toJSONString(user1);
            ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
            opsForValue.set("SESSION:" + token,userString,30*60, TimeUnit.SECONDS);
            String stringUser = opsForValue.get("SESSION:" + token);
            return token;
        }
         return null;
    }

    @Override
    public User getUserByToken(String token) {
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        String stringUser = opsForValue.get("SESSION:" + token);
        System.out.println(stringRedisTemplate.getExpire("SESSION:" + token));
        User user = JSON.parseObject(stringUser, User.class);
        return user;
    }


}
